/**
 * setup JQuery's AJAX methods to setup CSRF token in the request before sending it off.
 * http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
 */

function getCookie(name)
{
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?

            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

$(document).ready(function(){

    $('link[title=icons]').prop('disabled',true);
    $('link[title=icons]').prop('disabled',false);

    var overlay = $('#overlay');
    var message_box = $('#message_box');

    overlay.click(function(){
        message_box.fadeOut();
        overlay.fadeOut();

    });

    $(document).keyup(function(e){
       if (e.keyCode == 27){
           $('#message_box').fadeOut();
           $("#overlay").fadeOut();       }
           if ($('#share-deal-wrap').is(':visible')){
                $('#share-deal-wrap').slideToggle();
           }
    });
    // Add markItUp! to your textarea in one line
    // $('textarea').markItUp( { Settings }, { OptionalExtraSettings } );
    var martkitup = $('#markItUp');
    if (martkitup.is(':visible')){
	    martkitup.markItUp(mySettings);
    }
    
    // You can add content from anywhere in your page
    // $.markItUp( { Settings } );	
    $('.add').click(function() {
        $.markItUp( { 	openWith:'<opening tag>',
                        closeWith:'<\/closing tag>',
                        placeHolder:"New content"
                    }
                );
        return false;
    });
    
    // And you can add/remove markItUp! whenever you want
    // $(textarea).markItUpRemove();
    $('.toggle').click(function() {
        if ($("#markItUp.markItUpEditor").length === 1) {
            $("#markItUp").markItUpRemove();
            $("span", this).text("get markItUp! back");
        } else {
            $('#markItUp').markItUp(mySettings);
            $("span", this).text("remove markItUp!");
        }
        return false;
    });
    $(".link").click(
        function(e) {
            e.preventDefault();
            var f = $("#markItUp");
            f.val("[quote=" + "[/quote]\n");
            f.focus();
    });
    $(".post_comment").click(
        function(e) {
            e.preventDefault();
            var f = $("#markItUp");
            f.val("");
            f.focus();
    });  
    $('#login-trigger').click(function(){
            $(this).next('#login-content').slideToggle();
            $(this).toggleClass('active');                                  
    if ($('#login-trigger').hasClass('active')){
        $('#login-arrow').removeClass('small-down-arrow');
        $('#login-arrow').addClass('small-up-arrow');
    } else {
        $('#login-arrow').addClass('small-down-arrow');
        $('#login-arrow').removeClass('small-up-arrow');      	
    }
    });
    
    // Swapping Side bar
    $('.snapshot-title').click(function(){
        var id = $(this).attr('id');
        var type = id.replace("snapshot-title-","");
        var tablename = "";
        tablename = "#snapshot-table-" + type;
        
        $('.visible-table').each(function(){
            $(this).removeClass("visible-table");
            var temp = $(this).attr('id');
            temp = temp.replace("snapshot-table-","");
            $('#snapshot-title-'+temp).removeClass('selected');
        });
        $(tablename).addClass("visible-table");
        $(this).addClass('selected');        
        switch (type){
            case "1":
                text = "Hottest Today";
                break;
            case "2":
                text = "Hottest This Week";
                break;
            case "3":
                text = "Hottest This Month";
                break;
            case "4":
                text = "Hottest All Time";
                break;
            default:
                text = "Hottest Today";
                break;                            
        }
        $('#snapshot-header h5').html(text);
    });
    
    // Click on Comments page nav
    $('.comments-page-trigger').click(function(){
        $(this).parent().children('.comments-page').slideToggle().delay(200);
    });
    $('.comments-pp-trigger').click(function(){
        $(this).parent().children('.comments-pp').slideToggle().delay(200);
    });  
    
    $('.quote-reply').click(function(){
        var martkitup = $("#markItUp");
        var temp = martkitup.val();
        var value = '';
        var user = '';
        if ($(this).hasClass('post-quote')){
            var post = $('#post-content');
            value = unescape(unescape(post.html()));
            user = unescape(unescape($('#post-detail-user').html()));
        } else{
            var comparent = $(this).parent().parent().parent();
            value = unescape(unescape($(comparent).children('.comment-detail').html()));
            user = unescape(unescape($(this).parent().parent().children('.left').children('a').html()));
            //var user = userhtml.match(/.*?<a class="bold italic">(.*?)<\/a>/)[1]
        }
        value = value.replace(/(<.*?>)\n/g,'$1');
        value = value.replace(/>[\t ]+</g,'><');
        value = value.replace(/\t+/g,'');
        value = value.replace(/\n[ ]+/g,'\n');
        value = value.replace(/>[ ]+/g,'>');
        // Replce /" with "
        value = value.replace(/\\"/g,'"');
        // Remove non - chars
        value = value.replace(/[^A-Za-z0-9_\-\$%,\.\(\)\*&!@=<>""''\t \/\n]:/g,'');
        //Replace bbcode header       
        value = value.replace(/<div class=\"bbcode-quote\">\s*<div class=\"bbcode-quote-head\">(.*?)<\/div>/g,'[quote=$1]');
        // Replace bbcode body
        value = value.replace(/<div class="bbcode-quote-body">([\s\S]*?)<\/div>/g,'[bbody]$1[/bbody]');
        // Replace not required a element
        value = value.replace(/<a class="expand-quote">View full quote<\/a>/g,'');        
        value = value.replace(/<\/div>/g,'[/quote]');
        
        // Replace allowed elements with respective tags
        value = value.replace(/<b>/g,'[b]');               
        value = value.replace(/<\/b>/g,'[/b]');               
        value = value.replace(/<i>/g,'[em]');               
        value = value.replace(/<\/i>/g,'[/em]');            
        value = value.replace(/<u>/g,'[u]');               
        value = value.replace(/<\/u>/g,'[/u]');            
        value = value.replace(/<br>/g,'\n');

        // For non firefox
        value = value.replace(/<img.*?src="(.*?)".*?\/>/g,'[img]$1[/img]');
        //value = value.replace(/<img.*?".*?".*?src="(.*?)".*?>/g,'[img]$1[/img]');
        value = value.replace(/<img.*?(src|SRC)="(.*?)".*?>/g,'[img]$2[/img]');
        value = value.replace(/<a.*?href="(.*?)".*?>(.*?)<\/a>/gi,'[url="$1"]$2[/url]');

        // Replace multiple spaces to one space.
        value = value.replace(/\n[ \r\t]*?\n/g,'\n');
                
        // This shall be the last replacement, which replaces all other tags with spaces
        value = value.replace(/<.*?>(.*?)<\/.*?>/g,'$1');            
        
        // Replace any single tags like code comments or img tags
        value = value.replace(/<.*?>/g,'');            
        martkitup.val(temp+'[quote='+user+']'+value+'[/quote]');
        martkitup.focus();
    });

    $('a.has_tooltip').hover(function(){
        var title = $(this).attr('title');
        if (title){
            var help_id = '#tooltip';
            var h = parseInt($(window).height());
            var w = parseInt($(window).width());
            var pos = $(this).position();
            var input_v = parseInt(pos.top);
            var input_h = parseInt(pos.left);
            var help_v = input_v - 46;
            var help_h = input_h + 80;
            help_v = (parseInt($(help_id).width()) > 339) ? help_v - 13 : help_v;
            $(help_id).css('top', help_v);
            $(help_id).css('left', help_h);
            $(help_id).html(title+'<span class="border"></span>');
            $(help_id).css('display', 'inline-block');
        }
    });

    $.fn.display_tooltip = function(help_id, thisobj){
        if ($(help_id).html()){
            var h = parseInt($(window).height());
            var w = parseInt($(window).width());
            var pos = thisobj.position();
            var input_v = parseInt(pos.top);
            var input_h = parseInt(pos.left);
            var help_v = input_v - 46;
            var help_h = input_h + 80;
            help_v = (parseInt($(help_id).width()) > 339) ? help_v - 13 : help_v;
            $(help_id).css('top', help_v);
            $(help_id).css('left', help_h);
            $(help_id+'+span.help_text_border').css('top', help_v + ((parseInt($(help_id).width()) > 339) ? 46 : 31));
            $(help_id+'+span.help_text_border').css('left', help_h+10);
            $(help_id+'+span.help_text_border').css('display', 'block');
            $(help_id).css('display', 'inline-block');
        }
    };

    // help text dialog
    $("div.login_reg_form input, div.login_reg_form textarea").focus(function(){
        help_id = '#'+$(this).attr('id')+'_help';
        $.fn.display_tooltip(help_id, $(this));
    });

    $("div.login_reg_form input, div.login_reg_form textarea").focusout(function(){
        $('#'+$(this).attr('id')+'_help').css('display', 'none');
        $('#'+$(this).attr('id')+'_help+span.help_text_border').css('display', 'none');
    });

    $('#post_comment_form').submit(function(e){
        var serializeData = $('#post_comment_form').serialize();
        var comment = $('#markItUp').val();
        var markitup = $('#markItUpMarkItUp');
        var post_comm = $('#post_comment_msg');
        var wrap = $('#editor-wrap');
        wrap.removeClass('loading');
        post_comm.removeClass('success');
        post_comm.removeClass('failure');
        post_comm.addClass('visible');
        post_comm.removeClass('invisible');
        var post_type = $('#post_type').val();
        wrap.addClass('loading');
        markitup.addClass('loading');
        post_comm.html('Please wait...');
        setTimeout(function(){
        if ($('#post_email').length != 0){
            var email = $('#post_email').val();
            if (!email || !comment){
                 post_comm.html('Email and Comment must be entered');
                 post_comm.removeClass('invisible');
                 post_comm.addClass('visible');
                 post_comm.addClass('failure');
                 wrap.addClass('failure');
                 wrap.removeClass('loading');
                 markitup.removeClass('loading');
                 return false;
            }
        }

        if (!comment){
           post_comm.html('Comment must be entered');
           post_comm.removeClass('invisible');
           post_comm.addClass('visible');
           post_comm.addClass('failure');
            wrap.removeClass('loading');
            markitup.removeClass('loading');
            return false;
        }

        var urltopost = '/asja/postcomment/'+post_type+'/'+$('#post_id').val();
        $.ajax({
            type: 'POST',
            url: urltopost,
            data: serializeData,
            cache: 'false',
            dataType: 'json',
            async: 'true',

            success: function(data){
                post_comm.html(data.message);
                post_comm.removeClass('invisible');
                post_comm.addClass('visible');
                if (Boolean(data.status)){
                    post_comm.addClass('success');
                } else{
                    post_comm.addClass('failure');
                }
            }})
        wrap.removeClass('loading');
        markitup.removeClass('loading');
    }, 2000);
        return false;
    });

    $('span.vote.active, span.vote.disabled').click(function() {
        var vote_div = $(this).parent().parent();
        var left = vote_div.offset().left;
        var top = vote_div.offset().top - 20;
        var default_msg = 'Thanks for showing interest in helping the community by voting. But in order to avoid ' +
            'scams we request you to kindly <a href="/login">login/register</a>';
        var spanel = $(this).parent().parent().children('span.hotness');
        var message_box = $('#message_box');
        var message_box_msg = $('#message_box_msg');
        message_box_msg.removeClass('failure');
        message_box_msg.removeClass('success');
        message_box_msg.removeClass('loading');
        overlay.show();

        message_box.css({
             'top': top,
             'left': left
        });
        message_box.fadeIn(500);
        if ($(this).hasClass('disabled')){
            message_box_msg.html(default_msg);
            message_box_msg.addClass('failure');
        } else{
            var vote_div_id = vote_div.attr('id');
            var temp = vote_div_id.split('_');
            var urltopost = '/asja/vote/' + temp[1];
            message_box_msg.html('');
            message_box.addClass('loading');
            var type = ($(this).hasClass('large-down-arrow')) ? 'down' : 'up';
            var thiss = $(this);
            setTimeout(function(){
                $.ajax({
                    type: 'POST',
                    url: urltopost,
                    data: {
                        'vote_type': type,
                        'post_id': temp[2]
                    },
                    cache: 'false',
                    dataType: 'json',
                    async: 'true',

                    success: function(data){
                        message_box.removeClass('loading');
                        message_box_msg.html(data.message);
                        if (Boolean(data.status)){
                            message_box_msg.addClass('failure');
                        } else{
                            spanel.html(data.temp+'&deg;');
                            message_box_msg.addClass('success');
                            thiss.removeClass('active');
                            thiss.removeClass('cur-pointer');
                            thiss.addClass('inactive');
                            thiss.attr('title', 'You have already voted');
                            var thissib = thiss.parent().siblings('a').children('span');
                            thissib.removeClass('active');
                            thissib.removeClass('cur-pointer');
                            thissib.addClass('inactive');
                            thissib.attr('title', 'You have already voted');
                        }
                    }
                });
            }, 2000);
        }
    });

    $('a.like-unlike.enabled').click(function() {
        var vote_div = $(this).parent();
        var left = vote_div.offset().left;
        var top = vote_div.offset().top - 20;
        var default_msg = 'Thanks for showing interest in helping the community by voting. But in order to avoid ' +
            'scams we request you to kindly <a href="/login">login/register</a>';
        var message_box = $('#message_box');
        var message_box_msg = $('#message_box_msg');
        message_box_msg.removeClass('failure');
        message_box_msg.removeClass('success');
        message_box_msg.removeClass('loading');
        overlay.show();

        message_box.css({
             'top': top,
             'left': left
        });
        message_box.fadeIn(500);
        var vote_div_id = $(this).attr('id');
        var temp = vote_div_id.split('-');
        var urltopost = '/asja/like';
        message_box_msg.html('');
        message_box.addClass('loading');
        var type = ($(this).hasClass('unlike')) ? 'down' : 'up';
        var thiss = $(this);
        var thissib = thiss.siblings('a.like-unlike');
        setTimeout(function(){
            $.ajax({
                type: 'POST',
                url: urltopost,
                data: {
                    'vote_type': type,
                    'post_id': temp[2]
                },
                cache: 'false',
                dataType: 'json',
                async: 'true',

                success: function(data){
                    message_box.removeClass('loading');
                    message_box_msg.html(data.message);
                    if (Boolean(data.status)){
                        message_box_msg.addClass('failure');
                    } else{
                        message_box_msg.addClass('success');
                        if (type == 'down'){
                            var textval = "unliked"
                        }else {
                            var textval = "liked"
                        }
                        thiss.removeClass('enabled');
                        thiss.addClass('disabled');
                        thiss.attr('data-icon', '');
                        thiss.attr('title', 'You '+textval+' this comment');
                        thiss.html(textval.toUpperCase());
                        thissib.remove();
                    }
                }
            });
        }, 2000);
    });

    $('#message_box').click(function(){
       $('#message_box').fadeOut();
       $("#overlay").fadeOut();
    });

    $.ajaxSetup({
         beforeSend: function(xhr, settings) {
             if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                 // Only send the token to relative URLs i.e. locally.
                 xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
             }
         }
    });

    $('#sorting').change(function(){
        var val = $(this).val();
        var fullpath = location.pathname + location.search;
        fullpath = fullpath.replace(/sort=([a-zA-Z0-9]+?)&/gi, 'sort='+val+'&');
        fullpath = fullpath.replace(/sort=([a-zA-Z0-9]+?)$/gi, 'sort='+val);
        if (fullpath.search(/.*?sort.*?/) < 0){
          if (fullpath.search(/\?/) < 0){
            fullpath = fullpath + '?sort=' + val;
          }else{
            fullpath = fullpath + '&sort=' + val;
          }
        }
        window.open(fullpath, "_self");
    });

    var useredit = $('.user-edit');

    useredit.mouseover(function(){
        help_id = '#id_' + $(this).attr('id') + '_help';
        $.fn.display_tooltip(help_id, $(this));
    });

    useredit.mouseout(function(){
        $('#id_' + $(this).attr('id') + '_help').css('display', 'none');
        $('#id_' + $(this).attr('id') + '_help+span.help_text_border').css('display', 'none');
    });

    var locat = $('#locat-input').val();
    var descr = $('#descr-input').val();

    useredit.click(function(){
        var thisid = $(this).attr('id');
        var inputid = thisid + '-input';
        if (thisid == 'user-avatar-wrap'){
            // $('user-avatar-wrap-file').trigger('click');
            $('#user-save-buttons-wrap').slideDown();
        } else{
            $('#'+inputid).removeClass('disabled');
            $('#'+inputid).select();
            $('#user-save-buttons-wrap').slideDown();
        }
    });

    $('.user-save-button').click(function(){

       if ($(this).attr('value') == 'Cancel'){
            $('#locat-input').val(locat);
            $('#descr-input').val(descr);
            $('#user-avatar-wrap-file').val('');
            $('#user-avatar-wrap-file').css('opacity',0);
            $('.user-input').addClass('disabled');
           $(this).parent().slideUp();
       } else if ($(this).attr('value') == 'Save'){
            $('#descr-upload-val').val($('#descr-input').val());
            $('#locat-upload-val').val($('#locat-input').val());
            $('#user-avatar-wrap-form').submit();
            return false;
       }
    });

    $('#user-avatar-wrap-file').change(function (){
       $(this).css('opacity', 0.8);
    });

    $('#user-search-input, #id_posted_by').keyup(function(){
        var user_search = $(this).attr('id');
        var userslist = (user_search == 'user-search-input') ? $('#users-list') : $('#posted_by_list');
        if ($(this).val().length < 1){
            userslist.hide();
            return;
        }
        var urltopost = '/asja/user/search?userchar=' + $(this).val();
        if (user_search == 'id_posted_by'){
            urltopost = urltopost + '&from=search' + '&toput=' + user_search;
        }
        setTimeout(function(){
            $.ajax({
                type: 'GET',
                url: urltopost,
                cache: 'false',
                dataType: 'json',
                async: 'true',

                success: function(data){
                    if (Boolean(data.status)){
                        userslist.html('');
                    } else{
                        userslist.html(data.message);
                        userslist.show();
                        if (user_search == 'id_posted_by'){
                            userslist.delegate(".put-to-input", "click",  function(){
                                toput = $(this).attr('toput');
                                $('#'+toput).val($(this).text());
                                $(this).parent().parent().parent().hide();
                            });
                        }
                    }
                }
            });
        }, 500);
    });

    $('#store-search-input, #id_store').keyup(function(){
        var store_search = $(this).attr('id');
        var storeslist = (store_search == 'store-search-input') ? $('#stores-list') : $('#store_list');
        if ($(this).val().length < 1){
            storeslist.hide();
            return;
        }
        var urltopost = '/asja/store/search?storechar=' + $(this).val();
        if (store_search == 'id_store'){
            urltopost = urltopost + '&from=search' + '&toput=' + store_search;
        }
        setTimeout(function(){
            $.ajax({
                type: 'GET',
                url: urltopost,
                cache: 'false',
                dataType: 'json',
                async: 'true',

                success: function(data){
                    if (Boolean(data.status)){
                        storeslist.html('');
                    } else{
                        storeslist.html(data.message);
                        storeslist.show();
                        if (store_search == 'id_store'){
                            storeslist.delegate(".put-to-input", "click",  function(){
                                toput = $(this).attr('toput');
                                $('#'+toput).val($(this).text());
                                $(this).parent().parent().parent().hide();
                            });
                        }
                    }
                }
            });
        }, 500);
    });

    $('#main-search-input').keyup(function(){
        dealslist = $('#deals-list');
        deal_search = $('#main-search-input');
        if (deal_search.val().length < 2){
            dealslist.html('');
            return
        }

        urltopost = '/asja/find?dealchar=' + deal_search.val();
        setTimeout(function(){
            $.ajax({
                type: 'GET',
                url: urltopost,
                cache: 'false',
                dataType: 'json',
                async: 'true',

                success: function(data){
                    if (Boolean(data.status)){
                        dealslist.html('');
                    } else{
                        dealslist.html(data.message);
                    }
                }
            });
        }, 500);
    });

    $('.forgot_login_trigger').click(function(e){
        e.preventDefault();
        login_form = $('#login_form_wrap');
        if (login_form.is(":visible")){
            login_form.slideToggle(1200, function(){$('#forgot_form_wrap').slideToggle(800);});
        } else{
            $('#forgot_form_wrap').slideToggle(1200, function(){login_form.slideToggle(800);});
        }
    });

    var datepick = $('.datepicker');
    if (datepick.length > 0){
    var datepicks = $('.datepicker').pikaday({
        minDate: new Date('2012-01-01'),
        maxDate: new Date('2020-01-01'),
        yearRange: [2010,2020],
        format: 'YYYY-MM-DD'
    });
    datepicks.each(function (){
      $(this).toString(function(){
          date = $(this).val();
      });
    });
    }

    $('#iemsg_close').click(function(){
       $('#iemsg').slideUp(300);
    });

    $('.share-deal-trigger').click(function () {
        var thiss = $(this);
        var left = thiss.offset().left;
        var top = thiss.offset().top - 20;
        var wrap = $('#share-deal-wrap');
        wrap.css(
            {
                'left': left,
                'top': top
            }
        );
        wrap.slideToggle(300);
    });

});

